from survey import models
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect

# Create your views here.

def index(request):
    return render(request, 'survey/index.html')


def evaluate(request):
    if models.TestPaper.objects.filter(pk=1):
        allpaper = models.TestPaper.objects.all
    return render(request, 'survey/evaluate.html', {"alltestpapers":allpaper})

def usercheck(request):
    if request.method == 'POST':
        username_input = request.POST['username']
        telphone_input = request.POST['telphone']
        select_paper = request.POST['testpapers']
        print("user:{}, tel:{}, paper:{}.".format(username_input, telphone_input, select_paper))
        paper = models.TestPaper.objects.get(id = select_paper)
        if paper.answerpaper_set.filter(telphone = telphone_input):
            ans_paper = paper.answerpaper_set.get(telphone = telphone_input)
            return render(request, 'survey/usercheck.html', {"testpaper":paper, "answerpaper":ans_paper})
        else:
            ans_paper = models.AnswerPaper.objects.create(testee=username_input, telphone=telphone_input,  scores = 0, testpaper=paper)
            return render(request, 'survey/testpaper.html', {"testpaper":paper, "answerpaper":ans_paper})
    else:
        return HttpResponse("You already finish your test.")

def revieworredo(request, answerpaperid):
    if request.method == 'POST':
        review_or_redo = request.POST['revieworredo']
        print("review_or_redo:{}.".format(review_or_redo))
        if models.AnswerPaper.objects.filter(id = answerpaperid):
            ans_paper = models.AnswerPaper.objects.get(id = answerpaperid)
            paper = ans_paper.testpaper
            if review_or_redo == "redo":                
                return render(request, 'survey/testpaper.html', {"testpaper":paper, "answerpaper":ans_paper})
            else:
                return render(request, 'survey/result.html', {"testpaper":paper, "answerpaper":ans_paper})
    else:
        return HttpResponse("You already finish your test.")

def result(request, anspaperid):
    if request.method == 'POST':
        if models.AnswerPaper.objects.filter(id = anspaperid):
            ans_paper = models.AnswerPaper.objects.get(id = anspaperid)
            paper = ans_paper.testpaper
            for sub in paper.subject_set.all():
                choice_id_str = 'choice{}'.format(sub.id)
                print(choice_id_str)
                ops_id = int(request.POST[choice_id_str])
                anw = models.Answer.objects.create(sub_id = sub.id, options = ops_id, answerpaper = ans_paper )
                anw.save()
                print("title:{},subid:{}, ansubid:{}, answer:{}".format(sub.title, sub.id, anw.sub_id, anw.options))
            ans_paper.save()        
        return render(request, 'survey/result.html', {"testpaper":paper, "answerpaper":ans_paper})
    else:
        return HttpResponseRedirect('/')
    



